package com.OnTimeTeam.OnTime;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.TreeSet;

import android.content.Context;
import android.content.Intent;

import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

//////////////////////
//The list adapter - what makes the list to be arranged
public class RemindersList extends ArrayAdapter<String> {

	private TextView textMessage;
	private Toast toast;

	private LayoutInflater inflater;
	private RegularAlarmHolder holder;
    private static final int REGULAR_ITEM = 0;
    private static final int QUICK_ITEM = 1;
    private static final int SMART_ITEM = 2;
    private static final int TYPE_MAX_COUNT = 3;
	
    private TreeSet<Integer> quickItemsSet = new TreeSet<Integer>();
    private TreeSet<Integer> smartItemsSet = new TreeSet<Integer>();

	private ArrayList<String> items; //all alarms details
	
	private ArrayList<AlarmFeatures> alarms; //all alarms details
	private Context appContext; //the application context
	private Context baseContext;
	private String filePath;
	private TextView timeToNextAlarm;

	
	///////////////
	//CTOR - init' the array of AlarmFeatures and ApplicationContext object
    public RemindersList(Context context, int textViewResourceId, ArrayList<AlarmFeatures> alarms, ArrayList<String> items, Context appContext, Context baseContext, TextView timeToNextAlarm) {
        super(context, textViewResourceId);
        
        filePath = getContext().getFilesDir().getPath().toString() + "/reminders.xml";
		this.inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		
		final View toastView = inflater.inflate(R.layout.costum_toast,null);
		textMessage = (TextView)toastView.findViewById(R.id.addressConfirmation);
		toast = new Toast(getContext());
		toast.setView(toastView);
		toast.setGravity(Gravity.BOTTOM|Gravity.CENTER, 0, 150);
		toast.setDuration(Toast.LENGTH_SHORT);
		
        this.alarms = alarms;
        this.appContext = appContext;
        this.baseContext = baseContext;
        this.timeToNextAlarm = timeToNextAlarm;
        
        this.items = new ArrayList<String>();
		for(int i = 0; i < items.size(); ++i){
			if(items.get(i).equals("QUICK_ITEM"))
				addQuickItem(items.get(i));
			else if(items.get(i).equals("SMART_ITEM"))
				addSmartItem(items.get(i));
			else if(items.get(i).equals("REGULAR_ITEM"))
				addItem(items.get(i));
		}

    }
    
    public void removeItem(int index) {
    	
		
		items.remove(index); 
    	
		TreeSet<Integer> quickItemsSetTmp = new TreeSet<Integer>();
		Iterator<Integer> quickItr = quickItemsSet.iterator();
				
		while(quickItr.hasNext()) {
			
			int nextElm = quickItr.next();
			
			//STOP when getting to the wanted alarm
			if(nextElm < index)
				quickItemsSetTmp.add(nextElm);
			else if(nextElm > index)
				quickItemsSetTmp.add(nextElm - 1);
			
		}
		
	    quickItemsSet = quickItemsSetTmp;
	    
	    
		TreeSet<Integer> smartItemsSetTmp = new TreeSet<Integer>();
		Iterator<Integer> smartItr = smartItemsSet.iterator();
		while(smartItr.hasNext()) {
			
			int nextElm = smartItr.next();
			
			//STOP when getting to the wanted alarm
			if(nextElm < index)
				smartItemsSetTmp.add(nextElm);
			else if(nextElm > index)
				smartItemsSetTmp.add(nextElm - 1);
		}

		smartItemsSet = smartItemsSetTmp;

	    notifyDataSetChanged();
    }
    

	public void addItem(final String item) {
		items.add(item);
	    notifyDataSetChanged();
	}
	
	public void addQuickItemOnStart(final String item) {
		
		items.add(0, item);
				
		TreeSet<Integer> quickItemsSetTmp = new TreeSet<Integer>();
		quickItemsSetTmp.add(0);
		
		
		Iterator<Integer> quickItr = quickItemsSet.iterator();
		while(quickItr.hasNext())
	    	quickItemsSetTmp.add(quickItr.next() + 1);
		
	    quickItemsSet = quickItemsSetTmp;
	    
	    
		TreeSet<Integer> smartItemsSetTmp = new TreeSet<Integer>();
		Iterator<Integer> smartItr = smartItemsSet.iterator();
		while(smartItr.hasNext())
			smartItemsSetTmp.add(smartItr.next() + 1);
		smartItemsSet = smartItemsSetTmp;
		
	    notifyDataSetChanged();
	}
	
	public void addQuickItem(final String item) {
		items.add(item);
	    // save separator position
		quickItemsSet.add(items.size() - 1);
		
	    notifyDataSetChanged();
	}
	
	public void addSmartItem(final String item) {
		items.add(item);
	    // save separator position
		smartItemsSet.add(items.size() - 1);
	    notifyDataSetChanged();
	}
		
		
	public int getItemViewType(int position) {
		if(quickItemsSet.contains(position))
			return QUICK_ITEM;
		else if(smartItemsSet.contains(position))
			return SMART_ITEM;
	    return REGULAR_ITEM;
	}
    @Override
    public int getViewTypeCount() {
        return TYPE_MAX_COUNT;
    }

    @Override
    public int getCount() {
        return items.size();
    }

    @Override
    public String getItem(int position) {
        return items.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }
		
    ////////////////////
    //This method sets the view of ONE item in the list (it gets it's index - it's the same index as the AlarmFeatures ArrayList)
    public View getView(final int index, View convertView, ViewGroup parent) {
       	
    	holder = null;
        int type = getItemViewType(index);
        
        if (convertView == null) {
        	switch(type) {
        	case REGULAR_ITEM:
        		holder = new RegularAlarmHolder();
        		convertView = inflater.inflate(R.layout.reminder_regular_item, null);//set the view to the res/layout/reminder_item.xml file
        		holder.labelTV = (TextView)convertView.findViewById(R.id.label);
        		holder.timeTV = (TextView) convertView.findViewById(R.id.time);
        		holder.daysTV = (TextView) convertView.findViewById(R.id.daysInWeek);
        		holder.status = (ImageView) convertView.findViewById(R.id.toggleButton1);
        		
        		break;
        	case SMART_ITEM:
        		holder = new SmartAlarmHolder();
        		convertView = inflater.inflate(R.layout.reminder_smart_item, null);//set the view to the res/layout/reminder_item.xml file
        		((SmartAlarmHolder)holder).routeButton = (ImageView)convertView.findViewById(R.id.routeDetails);
        		holder.labelTV = (TextView)convertView.findViewById(R.id.label);
        		holder.timeTV = (TextView) convertView.findViewById(R.id.time);
        		holder.daysTV = (TextView) convertView.findViewById(R.id.daysInWeek);
        		holder.status = (ImageView) convertView.findViewById(R.id.toggleButton1);
        		
        		
        		break;
        	case QUICK_ITEM:
        		holder = new RegularAlarmHolder();
        		convertView = inflater.inflate(R.layout.reminder_regular_item, null);//set the view to the res/layout/reminder_item.xml file
        		holder.labelTV = (TextView)convertView.findViewById(R.id.label);
        		holder.timeTV = (TextView) convertView.findViewById(R.id.time);
        		holder.daysTV = (TextView) convertView.findViewById(R.id.daysInWeek);
        		holder.status = (ImageView) convertView.findViewById(R.id.toggleButton1);
        		
        		break;
        	
        	
        	}
        	
    		convertView.setTag(holder);
        }
        else {
			switch (type) {
			case REGULAR_ITEM:
				holder = (RegularAlarmHolder)convertView.getTag();
				break;
			case QUICK_ITEM:
				holder = (RegularAlarmHolder)convertView.getTag();
				break;
			case SMART_ITEM:
				holder = (SmartAlarmHolder)convertView.getTag();
				break;
			}
        	
        }

        //get alarm features object by it's index
        final AlarmFeatures alarm = alarms.get(index);
        if (alarm == null)
        	return convertView;
        	
        holder.status.setFocusable(false);
        
        
    	if(alarm.getSortOfAlarm().equals("Quick")){
    		
    		if(alarm.getStatus().equals("On")) {
    			
        		String hourStr;
        		String minStr;
        		
        		int alarmHour = Integer.parseInt(alarm.getHour());
        		int alarmMin = Integer.parseInt(alarm.getMinute());
        		
        		if(alarmHour <= 9)
        			hourStr = "0" + Integer.toString(alarmHour);
        		else
        			hourStr = Integer.toString(alarmHour);

        		if(alarmMin <= 9)
        			minStr = "0" + Integer.toString(alarmMin);
        		else
        			minStr = Integer.toString(alarmMin);
        		
        		
        		holder.timeTV.setText(hourStr + ":" + minStr);
        		holder.daysTV.setVisibility(View.VISIBLE);
        		holder.daysTV.setText(alarm.getQuickInterval() + " " + getContext().getResources().getString(R.string.minutes));
    		

    		}
    		else {

        		holder.timeTV.setText(alarm.getQuickInterval() + " " + getContext().getResources().getString(R.string.minutes));
        		holder.daysTV.setVisibility(View.GONE);
    		}

    		holder.labelTV.setText(getContext().getResources().getString(R.string.quickAlarm));
    	}
    	else {
    		holder.timeTV.setText(alarm.getHour() + ":" + alarm.getMinute());
    		holder.labelTV.setText(alarms.get(index).getLabel());
    		holder.daysTV.setVisibility(View.VISIBLE);
    		
    		String days = alarms.get(index).getDaysToRepeat();
    		days = days.replace("Sun", getContext().getResources().getString(R.string.sun));
    		days = days.replace("Mon", getContext().getResources().getString(R.string.mon));
    		days = days.replace("Tue", getContext().getResources().getString(R.string.tue));
    		days = days.replace("Wed", getContext().getResources().getString(R.string.wed));
    		days = days.replace("Thu", getContext().getResources().getString(R.string.thu));
    		days = days.replace("Fri", getContext().getResources().getString(R.string.fri));
    		days = days.replace("Sat", getContext().getResources().getString(R.string.sat));
    		
    		if(days.split(", ").length == 7)
    			holder.daysTV.setText(getContext().getResources().getString(R.string.allWeek));
    		else
    			holder.daysTV.setText(days);
    	}
        
        if(alarm.getSortOfAlarm().equals("Smart")) {
        	((SmartAlarmHolder)holder).routeButton.setFocusable(false);
        	
        	((SmartAlarmHolder)holder).routeButton.setImageResource(R.drawable.googlemaps);
        	((SmartAlarmHolder)holder).routeButton.setBackgroundResource(R.drawable.round_button);
    		
    		final Intent intent = new Intent(getContext(), RouteDetailsTabHost.class);
    		intent.putExtra("ArrivalHour", ((SmartAlarmFeatures)alarm).getArrivalHour());
    		intent.putExtra("ArrivalMinute", ((SmartAlarmFeatures)alarm).getArrivalMinute());
    		intent.putExtra("Hour", ((SmartAlarmFeatures)alarm).getHour());
    		intent.putExtra("Minute", ((SmartAlarmFeatures)alarm).getMinute());
    		intent.putExtra("Origin", ((SmartAlarmFeatures)alarm).getOrigin());
    		intent.putExtra("Dest", ((SmartAlarmFeatures)alarm).getDest());
    		intent.putExtra("TTO", ((SmartAlarmFeatures)alarm).getTTO());
    		intent.putExtra("Transport", ((SmartAlarmFeatures)alarm).getTransport());
    		
    		//need to put instead of roadsQ - duration, distance, chosen track
    		if(((SmartAlarmFeatures)alarm).getTransport().equals("Transit"))
    		{
    			//intent.putExtra("roadsQ",(TransitRoadsQuery)((SmartAlarmFeatures)alarm).getRoadsQ());
    			intent.putExtra("distance",((SmartAlarmFeatures)alarm).getDistance());
    			intent.putExtra("duration",((SmartAlarmFeatures)alarm).getDuration());
    			//intent.putExtra("durationNumeric",((SmartAlarmFeatures)alarm).getDurationNumeric());
    			intent.putExtra("track",((SmartAlarmFeatures)alarm).getTrack());
    			
    		}
    		
    		
			((SmartAlarmHolder)holder).routeButton.setOnClickListener(new OnClickListener() {
    			public void onClick(View v) {
    				
    				if(isNetworkAvailable())
    					getContext().startActivity(intent);
    				else {
						textMessage.setText(getContext().getResources().getString(R.string.verifyNetworkConnection));
						toast.show();
    				}
    			}
    		});
        	
        }

    	//turn on/off the toggle-button according to the status of the alarm (On/Off)
		if(!RemindersIO.getSnoozeAlarmSign(alarm.getID(), filePath).equals("None"))
			holder.status.setImageResource(R.drawable.alarm_snooze);
    	else if(alarm.getStatus().equals("On"))
    		holder.status.setImageResource(R.drawable.alarm_active);
    	else
    		holder.status.setImageResource(R.drawable.alarm_off);


    	//define what happens when clicking the toogleButton
		holder.status.setOnClickListener(new OnClickListener() {

    		public void onClick(View v) {
    			if(alarm.getStatus().equals("On")) { //alarm is On - so we need to turn it Off
    				
    				//Handle snooze situation
    				String snoozeID = RemindersIO.getSnoozeAlarmSign(alarm.getID(), filePath);
    				if(!snoozeID.equals("None")){//IF SNOOZE
    					
    					AlarmFeatures tmpAF = new AlarmFeatures();
    					String id = snoozeID.split(",")[0];
    					tmpAF.setDaysIDS(id);
    					AlarmSetter.cancelExistingAlarm(tmpAF, appContext);
    					
    					RemindersIO.changeSnoozeSign(alarm.getID(), filePath, "None");
    					

        				AlarmSetter.cancelExistingAlarm(alarm, appContext);
        				if(alarm.getSortOfAlarm().equals("Regular"))
        					AlarmSetter.setBackAlarm(alarm, appContext, appContext);
        				else // Smart
        					AlarmSetter.setSmartAlarm((SmartAlarmFeatures)alarm, appContext);

    				}
    				else {
    					
        				//Change the alarm status in the XML file from "On" to "Off"
        				RemindersIO.changeAlarmStatus(filePath, Integer.toString(index), "Off");
        				
        				//Cancel the alarm through alarm-manager
        				AlarmSetter.cancelExistingAlarm(alarm, appContext);
        				
        				//set alarm status "Off"
        				alarm.setStatus("Off");
        				
        				holder.status.setImageResource(R.drawable.alarm_off);
    				}
    				
    			} 
    			else {// alarm is off - so we need to turn it On
    				
        			//Change the alarm status in the XML file from "Off" to "On"
        			RemindersIO.changeAlarmStatus(filePath, Integer.toString(index), "On");
        			
        			if(alarm.getSortOfAlarm().equals("Quick"))
        				SetQuickNap.updateTime(alarm, appContext, index);
        			else {
        				
        				AlarmSetter.cancelExistingAlarm(alarm, appContext);
        				if(alarm.getSortOfAlarm().equals("Regular"))
        					AlarmSetter.setBackAlarm(alarm, appContext, appContext);
        				else // Smart
        					AlarmSetter.setSmartAlarm((SmartAlarmFeatures)alarm, appContext);

        			}
    				
    				//set alarm status "On"
    				alarm.setStatus("On");
    				
    				holder.status.setImageResource(R.drawable.alarm_active);
    				
    			}
    			
    			ArrayList<AlarmFeatures> alarmsOn = new ArrayList<AlarmFeatures>();
    	        for(int i = 0; i < alarms.size(); ++i)
    	        	if(alarms.get(i).getStatus().equals("On"))
    	        		alarmsOn.add(alarms.get(i));
    	        if(alarmsOn.size() > 0) {
    	        	
    	        	String notification = NotificationService.getClosestAlarmString(alarmsOn, filePath);
    	        	notification = notification.replace("Next alarm set for", getContext().getResources().getString(R.string.nextAlarmSetFor));
    	        	notification = notification.replace("Sun,", getContext().getResources().getString(R.string.sunQ));
    	        	notification = notification.replace("Mon,", getContext().getResources().getString(R.string.monQ));
    	        	notification = notification.replace("Tue,", getContext().getResources().getString(R.string.tueQ));
    	        	notification = notification.replace("Wed,", getContext().getResources().getString(R.string.wedQ));
    	        	notification = notification.replace("Thu,", getContext().getResources().getString(R.string.thuQ));
    	        	notification = notification.replace("Fri,", getContext().getResources().getString(R.string.friQ));
    	        	notification = notification.replace("Sat,", getContext().getResources().getString(R.string.satQ));
    	        	notification = notification.replace("Today,", getContext().getResources().getString(R.string.todayQ));
    	        	if(!notification.equals(timeToNextAlarm.getText().toString())){
	    	        	timeToNextAlarm.setText(notification);
	    	        	timeToNextAlarm.setVisibility(View.VISIBLE);
	    	        	timeToNextAlarm.startAnimation(AnimationUtils.loadAnimation(getContext(), R.anim.fade_in));
    	        	}
    	        }
    	        else {
    	        	timeToNextAlarm.setText("");
    	        	timeToNextAlarm.setVisibility(View.GONE);
    	        }
    	        	
    			
    	        notifyDataSetChanged();
	            Intent notifyService = new Intent("com.OnTimeTeam.OnTime.NotificationService");
	            getContext().startService(notifyService);
    		}

    	});
    	
        /*Animation animation = null; 
        
        //animation = new TranslateAnimation(metrics.widthPixels/2, 0, metrics.widthPixels/2, 0); 
        animation = new ScaleAnimation((float)1.0, (float)1.0 ,(float)0, (float)1.0);
        animation.setDuration(200);  
        view.startAnimation(animation); 
        animation = null;  */
        
        //return the view of the item
        return convertView;
        
    }//end of method 'getView'
    
    public class RegularAlarmHolder{
    	public TextView labelTV;
    	public TextView timeTV;
    	public TextView daysTV;
    	public ImageView status;
    }

    public class SmartAlarmHolder extends RegularAlarmHolder{
    	public ImageView routeButton;
    }
    
	private boolean isNetworkAvailable() {
	    ConnectivityManager connectivityManager 
	          = (ConnectivityManager) getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
	    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
	    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
	}
	
	


}//EOF
